﻿using ApiDemo.Core.Dto.Input;
using ApiDemo.Core.Users;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ApiDemo.Auth.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AccountController : ControllerBase
    {

        private readonly UserManager<UserInfo> _userManager;
        private readonly SignInManager<UserInfo> _signInManager;
        public AccountController(
            UserManager<UserInfo> userManager,
            SignInManager<UserInfo> signInManager
            )
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }

        [HttpPost("Login")]
        public async Task<IActionResult> LoginAsync(LoginInputDto input)
        {

            try
            {
                var user =await _userManager.FindByNameAsync(input.UserName);
                await _signInManager.PasswordSignInAsync(user,input.Pwd,false,false);
                return Ok();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return Ok();
            }

        }

        [HttpPost("Regist")]
        public async Task<IActionResult> RegistAsync(RegistInputDto input)
        {
            var usreinfo = new UserInfo
            {
                UserName = input.UserName,
                Email = input.Email,
                PhoneNumber = input.Phone
            };
            var user = await _userManager.CreateAsync(usreinfo, "TestPwd123");
            return Ok(user);
        }

    }
}
